<template>
    <div class="upload-boxs">
        <input type="file" class="folder-upload" ref="folderUploadRef" directory mozdirector webkitdirectory accept="*"
            @change="getFile" style="display:none">
        <el-upload ref="fileUploadRef" class="upload-demo" :http-request="handleUploadRequest" multiple
            :limit="uploadFileLimit" :show-file-list="false" :on-exceed="handleExceed">
            <el-button ref="fileUploadButtonRef">{{ $t('message.buttons.upload') }}</el-button>
        </el-upload>
    </div>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    onBeforeUnmount,
    getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { useRouter } from "vue-router"
import { fileImport, bigFileUpload, saveFile, getUploadFolderKey, sendDirLastFile, bindUploadFile } from '@/api/common'
import useCommonStore from '@/store/common.js'
import { uploadByPieces } from "@/utils/uploadFile";
import type { uploadFile } from '@/types/common'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const commonStore = useCommonStore()
const router = useRouter();
const props = defineProps({
    parentId: {
        tyep: String,
        default: ''
    }
})
const uploadFileLimit = window.pluginConfig.uploadFileLimit || 5
const uploadBindKeyObj = ref<{ start: number | undefined, end: number | undefined }>({})
const uploadFileList = ref<uploadFile[]>([])
const bindFileList = ref<any[]>([])
const newuploadFileList = ref<any[]>([])
const bindFileNum = ref(0)
const folderUploadRef = ref()
const fileUploadButtonRef = ref()
const parentId = ref('')
const fileUploadRef = ref()
onMounted(() => {
    proxy.$eventBus.$on('clearUploadFinish', clearUploadFinish)
    proxy.$eventBus.$on('clearFileLsit', clearFileLsit)
})
onBeforeUnmount(() => {
    proxy.$eventBus.$off('clearUploadFinish', clearUploadFinish)
    proxy.$eventBus.$off('clearFileLsit', clearFileLsit)
})
function clearFileLsit() {
    uploadFileList.value = []
}
function clearUploadFinish(val) {
    fileUploadRef.value?.clearFiles()
}
// 文件夹上传
function getFile(event) {
    if (commonStore.fileList.length == 0) {
        proxy.$openFileUpload({
            parentId: parentId.value
        })
    }
    let currentDirKey: any = null
    getUploadFolderKey().then(res => {
        if (res.data.code == 0) {
            currentDirKey = res.data.data
            // 记录当前批次的个数
            uploadBindKeyObj.value[currentDirKey] = {
                start: 0,
                end: event.target.files.length
            }
            for (let i = 0; i < event.target.files.length; i++) {
                let file = event.target.files[i]
                if (file && file.name) {
                    let filePush = true
                    uploadFileList.value.forEach((item) => {
                        if (file.lastModified === item.file.lastModified) {
                            filePush = false
                        }
                    })
                    // 用于判断是否同批次的文件是否重复上传
                    if (filePush || true) {
                        let nameSuffixArr = file.name.split('.')
                        uploadFileList.value.push({
                            parentId: parentId.value,
                            currentDirKey: currentDirKey,
                            file: file,
                            fileName: file.name,
                            type: 'document_upload',
                            fileType: file.type,
                            nameSuffix: nameSuffixArr[nameSuffixArr.length - 1],
                            uid: file.uid || file.lastModified,
                            uploadTime: new Date().getTime(),
                            percentage: 0,
                            isMate: false,
                            isUpload: false,
                            isFinish: false
                        })
                        startUploadList({ file: file }, uploadFileList.value[uploadFileList.value.length - 1])
                        commonStore.setUploadFileList(uploadFileList.value)
                    }
                }
            }
        }
    })
}
function startUploadList(file, item) {
    if (file.file.size / 1024 / 1024 >= 20) {
        uploadByPieces({
            files: [file.file],
            pieceSize: window.pluginConfig.fileUploadPiece,
            progress: (num: string, prFile: File) => {
                item.percentage = parseInt(num) >= 98 ? 98 : parseInt(num)
                item.isUpload = true
                commonStore.setUploadFileList(uploadFileList.value)
            },
            success: (data: any) => {
                if (file.file.webkitRelativePath) {
                    bindFileList.value.push({
                        bucketName: data.bucketName,
                        fileName: data.fileName,
                        originalFileName: data.name,
                        originalName: data.name,
                        size: data.size,
                        filePath: file.file.webkitRelativePath.replace(`/${data.name}`, ''),
                        key: item.currentDirKey
                    })
                    newuploadFileList.value.push(item)
                    if (bindFileNum.value == 0) {
                        bindUploadFileFun(newuploadFileList.value.shift(), bindFileList.value.shift())
                    }
                } else {
                    saveFile(parentId.value, {
                        bucketName: data.bucketName,
                        fileName: data.fileName,
                        originalName: data.name,
                        size: data.size,
                    }).then(res => {
                        if (res.data.code == 0) {
                            item.docId = res.data.data.id
                            item.knowledgeId = res.data.data.knowledgeId
                            uploadSuccess(item)
                        }
                    })
                }
            },
            error: (err) => {
                if (file.file.webkitRelativePath) {
                    uploadLastSend(item.currentDirKey)
                }
                uploadError(item)
            }
        })
    } else {
        let fetchForm = new FormData()
        fetchForm.append("file", file.file, file.file.name)
        fetchForm.append("module", "/jvs-knowledge-ui/jvs-knowledge-import/")
        let fun = fileImport
        let type: string | number | undefined = parentId.value
        if (file.file.webkitRelativePath) {
            fun = bigFileUpload
            type = 'jvs-document-file'
        }
        fun(fetchForm, type, (e) => {
            item.percentage = parseInt(e) >= 98 ? 98 : parseInt(e)
            item.isUpload = true
            commonStore.setUploadFileList(uploadFileList.value)
        }, parentId.value).then(res => {
            if (file.file.webkitRelativePath) {
                let webkitRelativePath = file.file.webkitRelativePath
                bindFileList.value.push({
                    ...res.data.data,
                    originalName: res.data.data.name,
                    name: res.data.data.originalFileName,
                    filePath: webkitRelativePath.replace(`/${res.data.data.originalFileName}`, ''),
                    key: item.currentDirKey
                })
                newuploadFileList.value.push(item)
                if (bindFileNum.value == 0) {
                    bindUploadFileFun(newuploadFileList.value.shift(), bindFileList.value.shift())
                }
            } else {
                item.docId = res.data.data.id
                item.knowledgeId = res.data.data.knowledgeId
                uploadSuccess(item)
            }
        }).catch(err => {
            if (file.file.webkitRelativePath) {
                uploadLastSend(item.currentDirKey)
            }
            uploadError(item)
        })
    }
}
// 绑定文件
async function bindUploadFileFun(item: any, currentUpload: any) {
    bindFileNum.value = 1
    await sleep(500)
    if (!currentUpload) return
    // if(bindFileNum.value!=0) return
    // while(bindFileList.value.length>0){
    // if(bindFileNum.value == 0){
    // let currentUpload = bindFileList.value.shift()
    bindUploadFile({
        parentId: parentId.value,
        key: currentUpload.key,
        filePath: currentUpload.filePath,
        fileName: currentUpload.originalFileName,
        baseFile: currentUpload
    }).then(res => {
        item.docId = res.data.data.id
        item.knowledgeId = res.data.data.knowledgeId
        uploadSuccess(item)
        uploadLastSend(currentUpload.key)
    }).catch(err => {
        uploadLastSend(currentUpload.key)
    })
    // }
    // }
}
// 休眠
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}
// 上传成功
function uploadSuccess(item: any) {
    item.percentage = 100
    item.isfail = false
    item.isFinish = true
    bindFileNum.value = 0
    bindUploadFileFun(newuploadFileList.value.shift(), bindFileList.value.shift())
    commonStore.setUploadFileList(uploadFileList.value)
}
// 上传失败
function uploadError(item: any) {
    item.isFinish = true
    item.isfail = true
    bindFileNum.value = 0
    bindUploadFileFun(newuploadFileList.value.shift(), bindFileList.value.shift())
    commonStore.setUploadFileList(uploadFileList.value)
}
// 上传到最后一个发送通知
function uploadLastSend(key: string | number) {
    uploadBindKeyObj.value[key].start += 1
    bindFileNum.value = 0
    if (uploadBindKeyObj.value[key].start >= uploadBindKeyObj.value[key].end) {
        sendDirLastFile(key).then(res => { })
    }
}
function handleExceed() {
    proxy.$notify({
        title: $t('message.prompt'),
        message: `${$t('message.message.checkMaxFile1')}${uploadFileLimit}${$t('message.message.checkMaxFile2')}`,
        type: 'warning',
        position: 'bottom-right'
    });
}
// 调用文件上传的事件，选择文件
function fileUpload(val, id) {
    if (id) {
        parentId.value = id
    } else {
        parentId.value = props.parentId
    }
    if (val == 'file') {
        fileUploadButtonRef.value?.$.vnode.el?.click()
    } else {
        folderUploadRef.value.click()
    }
}
function handleUploadRequest(file, data) {
    if (commonStore.fileList.length == 0) {
        proxy.$openFileUpload({
            parentId: parentId.value
        })
    }
    let filePush = true
    uploadFileList.value.forEach((item) => {
        if (item.lastModified === file.file.lastModified) {
            filePush = false
        }
    })
    // 用于判断是否同批次的文件是否重复上传
    if (filePush || true) {
        let nameSuffixArr = file.file.name.split('.')
        uploadFileList.value.push({
            parentId: parentId.value,
            file: file.file,
            fileName: file.file.name,
            type: 'document_upload',
            fileType: file.file.type,
            nameSuffix: nameSuffixArr[nameSuffixArr.length - 1],
            uid: file.file.uid,
            uploadTime: new Date().getTime(),
            percentage: 0,
            isMate: false,
            isUpload: false,
            isFinish: false
        })
        startUploadList(file, uploadFileList.value[uploadFileList.value.length - 1])
        commonStore.setUploadFileList(uploadFileList.value)
    }
}
defineExpose({
    fileUpload
})
</script>
<style lang="scss" scoped>
.upload-boxs {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 0px;
    overflow: hidden;
}
</style>